<template>
  <div class="static-config-panel">
    <div class="panel-header">
      <el-button size="default"
        type="default"
        @click="handleFormatte">格式化</el-button>
      <el-button size="default"
        type="primary"
        @click="handleParse">解析数据</el-button>
      <el-button size="default"
        type="danger"
        @click="handleClear">清空</el-button>
    </div>
    <div class="panel-center">
      <el-alert :title="props.frontAlert"
        v-show="alertEnabled"
        :="alertAttrs" />
      <AceCodeEditor class="code-editor-panel"
        ref="aceEditorRef"
        :mode="modelStore.codeIsFunc ? 'javascript' : defaultMode"
        v-model="modelStore.codeContent" />
      <el-alert :title="props.behindAlert"
        v-show="alertEnabled"
        :="alertAttrs" />
    </div>
  </div>
</template>

<script setup>
import { AceCodeEditor } from '@/components/vf-editor'
import { reactive, computed, onBeforeMount, inject, nextTick, ref } from 'vue';
import XEUtils from 'xe-utils'
import { VfMessage } from '@/utils/vf-utils'
import { ElMessageBox } from 'element-plus';
import loadBeautifier, { beautifierOpts } from "@/utils/beautifierLoader"

const emits = defineEmits(['save', 'analysis'])
// 传递参数定义
const props = defineProps({
  // 编辑的内容
  editorValue: { type: String, default: '' },
  // 默认模式
  defaultMode: { type: String, default: 'javascript' },
  // 是否显示提示
  showAlert: { type: Boolean, default: true },
  // 是否显示切换按钮
  showSwitch: { type: Boolean, default: false },
  // 前置提示
  frontAlert: { type: String, default: 'func setStaticTableData() {' },
  // 后置提示
  behindAlert: { type: String, default: '}' },
});
const getTableConfigData = inject('getTableConfigData')
const optionModel = getTableConfigData().optionModel
// 编辑面板
const aceEditorRef = ref('')
const staticPre = 'return'
// 编辑器内容数据集
const modelStore = reactive({
  visible: false,
  funcMark: 'func:',
  codeIsFunc: props.showAlert,
  codeContent: '',
  // 字段数据
  fieldList: [],
})
// 提示组件是否启用
const alertEnabled = computed(() => {
  if (props.showSwitch) {
    return props.showAlert && modelStore.codeIsFunc
  } else {
    return modelStore.codeIsFunc
  }
})
// 提示子组件的属性
const alertAttrs = reactive({
  type: 'info',
  style: { padding: '5px 10px' },
  closable: false,
});
// 拼接return + 内容
const staticCodeContent = computed(() => {
  return staticPre + modelStore.codeContent
})
/** 初始化解析数据 */
const initStaticInfo = () => {
  const { dataConfig } = optionModel;
  const copyDataConfig = XEUtils.clone(dataConfig, true)
  let content = copyDataConfig.staticConfig?.content || '';
  modelStore.codeContent = content && content.includes(staticPre) ? content.replace(staticPre, '') : content
  modelStore.fieldList = copyDataConfig.fieldList;
};

/** 验证输入静态内容 */
const validateContent = () => {
  if (!modelStore.codeContent) {
    VfMessage.warning('请输入静态数据！');
    return false;
  }
  if (!Array.isArray(JSON.parse(modelStore.codeContent))) {
    VfMessage.warning('静态数据必须为数组格式！');
    return false;
  }
  return true
}
/**
 * 格式化
 */
const handleFormatte = () => {
  if (!validateContent()) return
  try {
    loadBeautifier(beautifier => {
      const formatContent = beautifier.js(modelStore.codeContent, { ...beautifierOpts.js })
      aceEditorRef.value.setValue(formatContent)
    })
  } catch (error) {
    console.error('静态数据格式化失败，存在未指定占位符，请检查！', error)
  }
}
/**
 * 解析数据
 */
const handleParse = () => {
  if (!validateContent()) return
  let finalResult = { fieldList: [] }
  finalResult.fieldList = handleStaticFieldList()
  if (XEUtils.isEmpty(modelStore.fieldList)) {
    emitsAnalysis(finalResult.fieldList, true)
  } else {
    ElMessageBox.confirm(
      '静态数据解析成功，存在字段配置，请选择操作？',
      '提示',
      {
        type: 'warning',
        appendTo: '.data-source-dialog',
        customClass: 'vf-message-box-confirm',
        cancelButtonText: '覆盖',
        confirmButtonText: '追加',
        closeOnClickModal: false,
        closeOnPressEscape: false,
      }
    ).then(() => {
      emitsAnalysis(finalResult.fieldList, false)
    }).catch(() => {
      emitsAnalysis(finalResult.fieldList, true)
    })
  }
}
/**
 * 向上触发analysis事件
 * 
 * @param fieldList 字段数据
 * @param isCover 是否覆盖
 */
const emitsAnalysis = (fieldList, isCover = false) => {
  // 数据赋值
  modelStore.fieldList = fieldList
  // 向上触发方法
  emits('analysis', {
    fieldColumns: fieldList,
  }, isCover);
}
/**清空 */
const handleClear = () => {
  nextTick().then(() => {
    modelStore.codeContent = ''
    aceEditorRef.value.setValue(modelStore.codeContent)
  });
}
/*** 梳理静态数据 */
const handleStaticFieldList = () => {
  const fieldItem = JSON.parse(modelStore.codeContent)[0]
  const filedList = []
  Object.keys(fieldItem).forEach(function (key) {
    const item = {
      field: key,
      title: key,
    }
    filedList.push(item)
  });
  return filedList
}

/** 保存按钮点击 */
const saveClick = () => {
  if (!validateContent()) return
  const result = {
    staticConfig: { content: staticCodeContent.value },
  };
  emits('save', XEUtils.clone(result, true));
};
onBeforeMount(() => {
  initStaticInfo();
});
defineExpose({
  saveClick,
});
</script>

<style lang="scss" scoped>
.el-alert {
  border: none;
}
.static-config-panel {
  height: 100%;
  padding: 0 8px;
  display: flex;
  flex-direction: column;
  .panel-header {
    height: 30px;
    margin: 0.6em 0;
    text-align: right;
    position: relative;
  }
  .panel-center {
    flex: auto;
    display: flex;
    flex-direction: column;
    margin-bottom: 6px;
  }
}
</style>